import React, { Component } from 'react';
import { connect } from 'dva';
import { Skeleton } from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import MenuView from '@/components/MenuView';
import isEmpty from 'lodash/isEmpty';
import { stringify } from 'querystring';

@connect(({ product, loading }) => ({
  currentService: product.currentService,
  loading: loading.effects['product/queryServiceById']
}))
class MainView extends Component {
  constructor(props) {
    super(props);
    this.state = {
      menuMap: {},
    };
  }

  componentDidMount() {
    const { location, dispatch } = this.props;
    if (location.query.serviceId) {
      dispatch({
        type: 'product/queryServiceById',
        payload: {
          pathParams: {
            id: location.query.serviceId,
          },
        },
      });
    }
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({ type: 'product/clearCurrentService' });
  }

  static getDerivedStateFromProps(props) {
    const { currentService, location } = props;
    let disabled = true;
    let query = '';
    let regionStart
    if (!isEmpty(currentService)) {
      disabled = false;
      query = stringify({
        serviceId: currentService.id,
        backRoute: location.query.backRoute,
      });
      regionStart = currentService.regionStart
    }
    const menuMap = {
      base: {
        path: `/product/${location.pathname.split('/')[2]}/service/base?${query}`,
        title: '基本信息',
      },
      // weightRule: {
      //   path: `/product/${location.pathname.split('/')[2]}/service/weightRule?${query}`,
      //   title: '计重规则',
      //   disabled,
      // },
      serviceScope: {
        path: `/product/${location.pathname.split('/')[2]}/service/serviceScope/${regionStart}?${query}`,
        title: '服务范围',
        disabled,
      },
      operationLog: {
        path: `/product/${location.pathname.split('/')[2]}/service/operationLog?${query}`,
        title: '操作日志',
        disabled
      },
    };
    return {
      menuMap,
    };
  }

  render() {
    const { children, loading, ...restProps } = this.props;
    let render;
    if (restProps.location.query.serviceId) {
      render = children
    } else {
      render = loading ? <Skeleton active /> : children
    }
    const { menuMap } = this.state;
    return (
      <PageHeaderWrapper title="返回" backRoute={restProps.location.query.backRoute}>
        <MenuView menuMap={menuMap} {...restProps}>
          {render}
        </MenuView>
      </PageHeaderWrapper>
    );
  }
}

export default MainView;
